<?php

class FormAction extends Action
{
    /**
     * undocumented function
     *
     * @return void
     * @author
     **/
    public function insert()
    {
        $Form = getCache('Form');

        $formid = I('post.formid', 0, 'intval');

        if (!$formid) {
            $this->error('缺少必要的参数！');
        }

        $tablename = $Form[$formid]['tablename'];

        $form_db = M($tablename);

        //确认表单数据未满10000条
        $count = $form_db->count('id');
        if ($count >= 10000) {
            exit;
        }

        $fields = getCache('FormField_' . $formid);

        foreach ($fields as $key => $res) {
            $res['setup'] = json_decode($res['setup'], true);
            $fields[$key] = $res;
        }

        $_POST['ip'] = get_client_ip();

        //验证码检测
        if ($Form[$formid]['captcha'] && (md5($_POST['verifyCode']) != $_SESSION['verify'])) {
            $this->error('验证码错误！');
        }

        $post = $_POST;
        import('ORG.Util.Verify');
        $verify = new Verify();
        $msg = '';
        foreach ($fields as $key => $val) {
            if ($val['required'] && empty($post[$val['field']])) {
                $this->error($val['name'] . '不能为空！');
                break;
            }

            switch ($val['pattern']) {
                case 'email': //电子邮件地址
                    if (!$verify->isEmail($post[$val['field']])) {
                        $this->error($val['name'] . '格式不正确！');
                    }
                    break;
                case 'url': //网址
                    if (!$verify->isUrl($post[$val['field']])) {
                        $this->error($val['name'] . '格式不正确！');
                    }
                    break;
                case 'mobile'://手机号码
                    if (!$verify->isMobile($post[$val['field']])) {
                        $this->error($val['name'] . '格式不正确！');
                    }
                    break;
            }

            $msg .= $val['name'] . ':' . $post[$val['field']] . '<br/>';
        }

        $post['create_time'] = time();

        if (!empty($_SESSION['user'])) {
            $post['user_id'] = $_SESSION['user']['id'];
            $post['username'] = $_SESSION['user']['username'];
        }

        $id = $form_db->add($post);

        if ($id !== false) {
            //是否发送邮件
            if ($Form[$formid]['sendmail']) {
                $lang = getlang();
                $config = getCache('Config_' . $lang);
                $email = C('mail_accept');
                sendmail($email, $config['site_name'], $msg);
            }
            $this->success('提交成功！');
        } else {
            $this->error(L('add_error') . ': ' . $form_db->getDbError());
        }
    }
}